
import { globalUtils } from '../../common/js/global-utils/global-utils-all';
import { uiUtils } from '../../common/js/ui-utils/ui-utils-all';
import Pure from 'pure-frontend';

/* SOURCE-CODE-START */

"use strict";


Pure.app.viewScope('role-management', function (scope) {
  var jqAuthorizeDialog;
  var jqMenuTree;

  scope.showAuthorizeDialog = function (view, roleId) {
    if (globalUtils.isNullOrUndefined(jqAuthorizeDialog)) {
      jqAuthorizeDialog = view.$ui('authorizeDialog');
      jqMenuTree = view.$ui('menuTree');

      // 添加对话框事件
      addDialogEvent(view);
    }

    // 记录角色ID
    uiUtils.dialog.setContextData(jqAuthorizeDialog, {
      roleId: roleId
    });

    // 显示弹出框
    uiUtils.dialog.showModal(jqAuthorizeDialog, {
      backdropParent: view.getViewElement(),
      onModalShow: function () {
        loadMenuTreeData(view, roleId, function (treeData) {
          setMenuTreeData(treeData);
        });
      }
    });
  };

  /**
   * 添加对话框事件
   * @param {*} view 
   */
  function addDialogEvent(view) {

    jqMenuTree.on('ready.jstree', function () {
      // 离开视图时检查表单数据是否改变
      uiUtils.view.checkFormDataChangeWhenLeave(scope, getSelectedFunctionIds);
    });

    jqAuthorizeDialog.on('hide.bs.modal', function () {
      // 不检查表单数据是否改变
      uiUtils.view.notCheckFormDataChangeWhenLeave(scope);
      // 重置树形控件
      jqMenuTree.jstree('destroy');
    });

    jqAuthorizeDialog.on('click', '.x-btn-confirm', function () {
      var dialogParams = uiUtils.dialog.getContextData(jqAuthorizeDialog);
      var roleId = dialogParams.roleId;
      var functionIds = getSelectedFunctionIds();

      var assignData = {
        roleId: roleId,
        functionIds: functionIds
      };

      // 调用远程接口分配功能
      view.callService('api/security/role/assignFunctions', assignData)
        .waitResult(function (result) {
          if (!uiUtils.common.checkWebResultSuccess(result)) {
            return;
          }

          uiUtils.dialog.hideModal(jqAuthorizeDialog);
          Pure.app.showMessage('${t("ui.system.common.msg.saveRecordSuccess")}');
        });
    });
  }

  /**
   * 返回选中的功能
   * @returns
   */
  function getSelectedFunctionIds() {
    // 获取选中的节点
    var selectedNodes = jqMenuTree.jstree('get_checked', true);
    var functionIds = [];

    // 获取选中的功能ID
    if (!globalUtils.isNullOrUndefined(selectedNodes)) {
      selectedNodes.forEach(function (node) {
        var nodeInfo = node.original.nodeInfo;

        if (nodeInfo.type === 'function') {
          functionIds.push(nodeInfo.data.id);
        }
      });
    }

    return functionIds;
  }

  /**
   * 设置菜单树的数据
   * @param {*} treeData 
   */
  function setMenuTreeData(treeData) {
    // 渲染树形控件
    jqMenuTree.jstree({
      'core': {
        'themes': {
          'icons': true
        },
        'data': treeData
      },
      'plugins': ['checkbox']
    });
  }

  /**
   * 加载菜单树的数据
   * @param {*} view 
   * @param {*} roleId 
   * @param {*} successFn 
   */
  function loadMenuTreeData(view, roleId, successFn) {
    // 获取当前菜单模板
    view.callService('api/menu/menuTemplate/getCurrentMenuTemplate')
      .waitResult(function (result) {
        if (!result.success) {
          Pure.app.showError(result.message);
          return;
        }

        var templateData = result.data;
        var templateId = templateData.id;

        // 获取该角色已分配的功能
        view.callService('api/security/role/listAssignedFunctions', {
          id: roleId
        }).waitResult(function (result) {
          if (!result.success) {
            Pure.app.showError(result.message);
            return;
          }

          var assignedFunctionData = result.data;
          var assignedFunctionIds = assignedFunctionData.map(function (record) {
            return record.id;
          });

          // 获取菜单列表
          view.callService('api/menu/menu/listHierarchyMenus', {
            id: templateId
          }).waitResult(function (result) {
            if (!result.success) {
              Pure.app.showError(result.message);
              return;
            }

            var templateName = templateData.templateName;
            var menuData = result.data;
            // 转换成树形数据
            var treeData = CurrentRunningApp.sharing.menu.convertToTreeData(menuData, function (node, type, data) {
              if (type === 'function') {
                node.state.selected = assignedFunctionIds.includes(data.id);
              }
            });

            treeData = [{
              text: templateName,
              icon: false,
              state: {
                opened: true
              },
              children: treeData,
              nodeInfo: {
                type: 'template',
                data: templateData,
                childMenus: menuData
              }
            }];

            successFn(treeData);
          });
        });
      });
  }

});

/* SOURCE-CODE-END */


